import logging

from case.models import CaseProgress
from case.utils import send_case_progress_to_client
from django.db.models.signals import post_save, post_delete, post_init
from django.dispatch import receiver
from office.models import Office

logger = logging.getLogger("django")

CONFIRM = 1


@receiver(post_save, sender=CaseProgress)
def send_case_progress(sender, instance, created, **kwargs):
    print("99999999999:", created)
    if not created:
        print(instance.confirm)
        if instance.confirm == CONFIRM:
            # 发送模板消息
            case = instance.case
            customers = case.customers.values_list("openid", flat=True)
            print("customers:", customers)
            s = set()
            if case.lead_lawyer:
                s.add(case.lead_lawyer.real_name)
            if case.assist_lawyer:
                s.add(case.assist_lawyer.real_name)
            if case.third_lawyer:
                s.add(case.third_lawyer.real_name)

            lawyer = ",".join(list(s))
            office = Office.objects.values("name", "telephone").first()
            print(office)
            data = {
                "reason": case.reason,
                "lawyer": lawyer,
                "progress": instance.progress.name,
                "openids": list(customers),
                "office_name": office.get("name", None) or "",
                "telephone": office.get("telephone", None) or "",
            }
            logger.info(data)
            send_case_progress_to_client(**data)

